package com.dk.shiro;

import com.dk.pojo.AdminUser;
import com.dk.pojo.User;
import com.dk.service.UserServiceI;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceI userServiceI;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println(">>>>>>>>>>>>>>>授权<<<<<<<<<<<<<<<<");
        //给资源进行授权
        SimpleAuthorizationInfo authorizationInfo  = new SimpleAuthorizationInfo();
        //查询数据库，获取表中权限串的所有值
        List<String> perms = new ArrayList<>();
        perms.add("delete");
        //将数据库查询出来的权限串添加到authorizationInfo
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }

    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println(">>>>>>>>>>>>>>>登录认证<<<<<<<<<<<<<<<<");

        //编写登录验证逻辑
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken; //强转可以获取封装参数值

        User user = userServiceI.selectGetAll(token.getUsername());


        //判断用户是否存在
        if(user == null){
            return null;
        }
        /*
        * 1.第一个user是登录成功放入session
        * 2.获取数据库密码，token会自动去校验页面传来的密码值
        * 3.比如说，登录成功，欢迎 某xx*/
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),user.getUname());
    }
}
